﻿//***************************************************************************
// Project:   MDT Wizard Studio
// File:      Variables.cs
// Purpose:   Form for displaying the variables passed into a wizard and the
//            values returned.
//
// Version:   3.0.1
//
// Change history:
// 2.0.0  mniehaus  10/11/2009  Created initial version.
//
// 3.0.0  mkoster   11/21/2012  Updated for MDT 2012. 
//
// 3.0.1  mkoster   11/22/2012  Added highlighting of changes.
//                              Made form resizable.
//
// 3.0.2  mkoster   01/11/2013  Renamed to MDT Wizard Studio
//***************************************************************************

namespace MDTWizardStudio   
{
    using System;
    using System.Diagnostics;
    using System.Drawing;
    using System.Globalization;
    using System.IO;
    using System.Windows.Forms;
    using System.Xml;

    /// <summary>
    /// Form for displaying the variables passed into a wizard and the
    /// values returned.
    /// </summary>
    internal partial class Variables : Form
    {
        #region Instance variables

        String _definitionFile;
        String _definitionDirectory;
        XmlDocument _oldVariables;

        #endregion Instance variables

        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        internal Variables()
        {
            InitializeComponent();
        }

        #endregion Constructor

        #region Internal properties

        /// <summary>
        /// Sets the full path of the definition file currently being edited.
        /// </summary>
        internal String DefinitionFile
        {
            set
            {
                _definitionFile = value;
                _definitionDirectory = Directory.GetParent(_definitionFile).FullName;
            }
        }

        #endregion Internal properties

        #region Event handlers

        private void VariablesLoad(object sender, EventArgs e)
        {
            // Clean up from previous execution
            if (Directory.Exists(@"C:\MININT"))
                Directory.Delete(@"C:\MININT", true);

            // Figure out the deployment share path
            string mdtDistributionDir =
                File.Exists(Directory.GetParent(_definitionDirectory).FullName + @"\Control\Version.xml")
                    ? Directory.GetParent(_definitionDirectory).FullName
                    : String.Empty;

            // Figure out the deployment share path
            //if (File.Exists(Directory.GetParent(_definitionDirectory).FullName + @"\Control\Version.xml"))
            //    mdtDistributionDir = Directory.GetParent(_definitionDirectory).FullName;
            //else
            //    mdtDistributionDir = String.Empty;

            // Run ZTIGather.wsf if it can be found
            var filePath = Utility.FindFile(_definitionDirectory, "ZTIGather.wsf");
            if (!String.IsNullOrEmpty(filePath))
            {
                var parameters = "\"" + filePath + "\" /localonly /DeploymentType:NEWCOMPUTER /DeploymentMethod:UNC";

                if (!String.IsNullOrEmpty(mdtDistributionDir))
                    parameters += " /DeployRoot:\"" + mdtDistributionDir + "\"";

                // Launch ZTIGather.wsf to get information about the current machine.  Have it shove in a few default
                // values too for DeploymentType, DeploymentMethod, and DeployRoot so that the wizard works better.
                var gatherProcess = new Process();
                var startInfo = new ProcessStartInfo("cscript.exe", parameters)
                                    {
                                        WindowStyle = ProcessWindowStyle.Normal,
                                        UseShellExecute = false
                                    };
                gatherProcess.StartInfo = startInfo;
                gatherProcess.Start();
                gatherProcess.WaitForExit();
            }

            // Load the variables
            LoadVariables();
        }

        private void RunClick(object sender, EventArgs e)
        {
            // Save the modified VARIABLES.DAT
            var variables = new XmlDocument();
            variables.LoadXml("<MediaVarList Version=\"4.00.5345.0000\" />");
            foreach (DataGridViewRow variableRow in variablesGrid.Rows)
            {
                if (variableRow.Cells[0].Value != null && variableRow.Cells[1].Value != null)
                {
                    var newVar = variables.CreateElement("var");
                    newVar.SetAttribute("name", variableRow.Cells[0].Value.ToString().ToUpper(CultureInfo.CurrentCulture));
                    newVar.AppendChild(variables.CreateCDataSection(variableRow.Cells[1].Value.ToString()));
                    if (variables.DocumentElement != null) variables.DocumentElement.AppendChild(newVar);
                }
            }
            variables.Save(@"C:\MININT\SMSOSD\OSDLOGS\VARIABLES.DAT");

            // Now run Wizard.hta if it can be found
            var filePath = Utility.FindFile(_definitionDirectory, "Wizard.hta");
            if (String.IsNullOrEmpty(filePath))
            {
                MessageBox.Show("Unable to test wizard because the files required could not be found.", "Unable to test wizard",
                    MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                return;
            }

            // Make sure the required files are present in the same directory
            foreach (var requiredFile in new[] {
                    "Wizard.hta", "Wizard.css", "WizUtility.vbs", "ZTIUtility.vbs", "ZTIConfigFile.vbs", 
                    "ZTIDataAccess.vbs", "ZTIDiskUtility.vbs", "ZTIBCDUtility.vbs", "ZTINicUtility.vbs", 
                    "Wizard.ico", "BackButton.JPG", "plusicon.gif", "minusico.gif", "SelectItem.jpg", 
                    "WelcomeBanner.jpg", "btnout.png", "btnover.png", "btnsel.png", "BackButton.png", 
                    "FolderIcon.png", "ItemIcon1.png", "MinusIcon1.png", "PlusIcon1.png", "SelectItem.png",
                    "header-image.png", "Computer.png", "Navbar.png", })
            {
                if (!File.Exists(_definitionDirectory + @"\" + requiredFile))
                {
                    filePath = Utility.FindFile(_definitionDirectory, requiredFile);
                    if (!String.IsNullOrEmpty(filePath))
                        File.Copy(filePath, _definitionDirectory + @"\" + requiredFile, true);
                }
            }

            // Launch Wizard
            var wizProcess = new Process();
            var startInfo = new ProcessStartInfo("mshta.exe", "\"" + _definitionDirectory + "\\Wizard.hta\" /definition:\"" + _definitionFile + "\" /debug:true")
                                {
                                    WindowStyle = ProcessWindowStyle.Normal,
                                    UseShellExecute = false
                                };
            wizProcess.StartInfo = startInfo;
            wizProcess.Start();
            wizProcess.WaitForExit();

            // Re-populate the variable list
            LoadVariables();

            // Clean up the MININT directory
            if (Directory.Exists(@"C:\MININT"))
                Directory.Delete(@"C:\MININT", true);

            // Switch the buttons and label
            buttonCancel.Enabled = false;
            buttonRun.Enabled = false;
            buttonClose.Visible = true;
            buttonClose.DialogResult = DialogResult.OK;
            labelVariables.Text = "Review the results of the wizard below.";
        }

        #endregion Event handlers


        #region Private methods

        private void LoadVariables()
        {
            // Load VARIABLES.DAT
            var variables = new XmlDocument();
            if (File.Exists(@"C:\MININT\SMSOSD\OSDLOGS\VARIABLES.DAT"))
            {
                variables.Load(@"C:\MININT\SMSOSD\OSDLOGS\VARIABLES.DAT");
            }
            else
            {
                variables.LoadXml("<MediaVarList Version=\"4.00.5345.0000\" />");
            }

            // Populate the data grid view
            variablesGrid.Rows.Clear();
            if (variables.DocumentElement != null)
                foreach (XmlNode variableNode in variables.DocumentElement)
                {

                    XmlNode oldVariable = null;
                    if (_oldVariables != null)
                    {
                        // Get old Variable
                        if (_oldVariables.DocumentElement != null)
                            if (variableNode.Attributes != null)
                                oldVariable = _oldVariables.DocumentElement.SelectSingleNode("var[@name='" + variableNode.Attributes["name"].Value + "']");
                    }

                    int rowID;

                    // Highlight changes to the variables by different background colors.
                    // We use the same background colors as being used in the InsideTS demo
                    if (oldVariable == null)
                    {
                        // New entry
                        if (variableNode.Attributes != null)
                        {
                            rowID = variablesGrid.Rows.Add(variableNode.Attributes["name"].Value, variableNode.InnerText, "");
                            if (_oldVariables != null)
                                variablesGrid.Rows[rowID].DefaultCellStyle.BackColor = Color.LightGreen;
                        }
                    }
                    else
                    {
                        // Existing entry, check for changed value
                        rowID = variablesGrid.Rows.Add(variableNode.Attributes["name"].Value, variableNode.InnerText, oldVariable.InnerText);
                        if (variableNode.InnerText != oldVariable.InnerText)
                            variablesGrid.Rows[rowID].DefaultCellStyle.BackColor = Color.Khaki;
                    }
                }

            // Properly size and display the columns
            variablesGrid.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            if (_oldVariables == null)
            {
                variablesGrid.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                variablesGrid.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                variablesGrid.Columns[2].Visible = false;
            }
            else
            {
                variablesGrid.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                variablesGrid.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                variablesGrid.Columns[2].Visible = true;
            }


            _oldVariables = variables;
        }

        #endregion Private methods
    }
}
